package com.android.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;

public class DownloadFile extends AsyncTask<String, Integer, String>
{
	private int bufferSize = 2048;

	private String url, fileName, destination;

	private OnDownloadInformation onDownloadInformation;

	public void setOnDownloadInformation(OnDownloadInformation onFileInformation)
	{
		this.onDownloadInformation = onFileInformation;
	}

	public void setBufferSize(int bufferSize)
	{
		this.bufferSize = bufferSize;
	}

	public DownloadFile(String url, String fileName, String destination)
	{
		this.url = url;
		this.destination = destination;
		this.fileName = fileName;
	}

	public void execute()
	{
		execute(url);
	}

	@Override
	protected String doInBackground(String... arg0)
	{
		try
		{
			URL url = new URL(arg0[0]);

			URLConnection connection = url.openConnection();

			connection.connect();

			publishProgress(connection.getContentLength(), 0);
			
			InputStream input = new BufferedInputStream(url.openStream());

			OutputStream output = new FileOutputStream(destination + File.separator + fileName);

			byte data[] = new byte[bufferSize];

			int total = 0;

			int count;

			while ((count = input.read(data, 0, bufferSize)) > 0)
			{
				total += count;
				publishProgress(total, 1);
				output.write(data, 0, count);
			}

			output.flush();
			output.close();
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onProgressUpdate(Integer... values)
	{
		super.onProgressUpdate(values);

		if (onDownloadInformation != null)
		{
			if (values[1].equals(0))
			{
				onDownloadInformation.onInformation(values[0]);
			}
			else if (values[1].equals(1))
			{
				onDownloadInformation.onProgress(values[0]);
			}
		}
	}
	
	@Override
	protected void onPostExecute(String result)
	{
		super.onPostExecute(result);
		if (onDownloadInformation != null)
			onDownloadInformation.onFinish();
	}

	public interface OnDownloadInformation
	{
		public void onInformation(int size);

		public void onProgress(int value);
		
		public void onFinish();
	}

}
